import os
import cv2
import json
import pandas as pd
import numpy as np
from glob import glob 
from tqdm import tqdm
from IPython import embed
import base64
from labelme import utils
image_path = "./shiyan/"
csv_file = "./a.csv" #split()的基础作用是分割字符串的。当没有参数输入的时候，它会默认空格、回车符（\n）、空格符(\t)，分割后形成列表保存分割结果。当输入参数的时候会根据参数进行分割。
#annotations = pd.read_csv(csv_file,header=None).values #os.sep表示的是分隔符的意思，Python中，windows的分隔符是 “\” 。Linux中的分隔符是 “/” 。
null = None
annotations = pd.read_csv(csv_file).values
total_csv_annotations = {}
for annotation in annotations:
    key = annotation[0].split(os.sep)[-1]
    value = np.array([annotation[1:]])
    if key in total_csv_annotations.keys():
        total_csv_annotations[key] = np.concatenate((total_csv_annotations[key],value),axis=0)
    else:
        total_csv_annotations[key] = value
        #开始打印
for key,value in total_csv_annotations.items():
    #print(cv2.imread(image_path+key).shape[:1])
    #height, width = cv2.imread(image_path + key).shape[:2]
    height, width = cv2.imread(image_path + key).shape[:2]
    labelme_format = {
    "version":"4.6.0",
    "flags":{},
    # "lineColor":[0,255,0,128],
    # "fillColor":[255,0,0,128],
    # "imagePath":key,
    # "imageHeight":height,
    # "imageWidth":width
    }
    # with open(image_path+key,"rb") as f:
    #     imageData = f.read()
    #     imageData = base64.b64encode(imageData).decode('utf-8')
    # #img = utils.img_b64_to_arr(imageData)
    # labelme_format["imageData"] = imageData
    shapes = []
    for shape in value:
        label = shape[-1]
        # s = {"label":label,"line_color":None,"fill_color":None,"shape_type":"rectangle"}
        #s = {"label": label, "group_id": null,  "shape_type": "rectangle"}
        s = {"label": label}
        points = [
            [shape[0],shape[1]],
            [shape[2],shape[3]]
            ]
        s["points"] = points
        s["group_id"] = null
        s["shape_type"] = "rectangle"
        s["flags"] = {}
        shapes.append(s)
        # s = {"label": label, "group_id": null, "shape_type": "rectangle"}
    labelme_format["shapes"] = shapes
    labelme_format["imagePath"] = key
    labelme_format["imageHeight"] = height
    labelme_format["imageWidth"] = width
    json.dump(labelme_format,open("%s/%s/"%(image_path,key.replace(".jpg",".json")),"w"),ensure_ascii=False, indent=2)